/*
** server.c
directions to execute
1. compile the program using G++ newserver.c
2. execute the code useing ./a.out
*/

//vector of sockets
// each new client get sockets
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <iostream>
#include <stdio.h>		
#include <sys/types.h>
#include <sys/socket.h> /* Definition of structures needed for sockets */
#include <netinet/in.h>
#include <sys/wait.h>
#include <netinet/in.h>	/* Definition of constants and structures for Internet Domain Addresses */
#include <sys/errno.h>
#include <sys/signal.h>
#include <string.h>
#include <values.h>

#define MAXDATASIZE 100	
using namespace std;
class server
{
	private:
	int sockfd;
	struct sockaddr_in self;
	struct sockaddr_in client_addr;
	socklen_t sin_size;
	int optval;
	char welcome_msg[BUFSIZ];
	

	public:
		void create_server();
		string server_recv();
		void server_send(char welcome_msg[BUFSIZ]);
		
};
int client_accepter = 0;
void server:: create_server()
{
	if((sockfd = socket(AF_INET, SOCK_STREAM,0)) < 0)
	{
		perror("Socket");
		exit(errno);
	}
	
	/*---Initialize address/port structure---*/
	memset((char*)&self,0, sizeof(self));
	self.sin_family = AF_INET;
	self.sin_port = htons(10000);
	self.sin_addr.s_addr = htons(INADDR_ANY);
	
	optval=1;
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, &optval, sizeof optval);
	/*---Assign a port number to the socket---*/
	if (bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0 )
	{
		perror("socket--bind");
		exit(errno);
	}

	/*---Make it a "listening socket"---*/
	if (listen(sockfd, 1) < 0 )
	{
		perror("socket--listen");
		exit(errno);
	}
	
	printf("server: waiting for connections...\n");
	int client_addr_length = sizeof(client_addr);
	if ((client_accepter = accept(sockfd, (struct sockaddr*)&client_addr, (socklen_t*)&client_addr_length)) < 0) 
	{
		perror("could not accept call");
	exit(1);
	}
	
}
// sprintf(welcome_msg,"Welcome to Single Client Telnet Server Demo\n\r");
    // if (write(client_socket_fd, &welcome_msg, strlen(welcome_msg)) < 0) {
    		// perror("write failed!");
	        // exit(1);
    // }

string server:: server_recv()
{
	char welcome_msg[BUFSIZ];
	int d = 0;
	memset((char*)&welcome_msg,0, sizeof(welcome_msg));
		//recieves from the client
	if(recv(client_accepter,welcome_msg,BUFSIZ,0))	
	{
		for(int i = 0; i < BUFSIZ; i++)
		{
			if(welcome_msg[i] == NULL)
			{
				char b[i-2];
				for(int t = 0; t < sizeof(b);t++)
				{
					b[t] = welcome_msg[t];
				}
				return b;
				
			}
		}
	}
	
}

void server:: server_send(char welcome_msg[BUFSIZ])
{
	if (write(client_accepter,welcome_msg, strlen(welcome_msg)) < 0) 
	{
    		perror("write failed!");
	        exit(1);
    }
}

